#include "tcpservice.h"

TcpService::TcpService(QObject *parent) : QTcpServer(parent)
{
    listclient=new QMap<qintptr,UserClient*>;
}
//if the client connect,this function will run
void TcpService::incomingConnection(qintptr socketDescriptor)
{
    locker.lock();
    UserClient *client=new UserClient(socketDescriptor);
    this->listclient->insert(socketDescriptor,client);
    connect(client,&UserClient::sendtoserver,this,&TcpService::receiveclient);
    connect(client,&UserClient::offline,this,&TcpService::deleteclient);
    connect(this,&TcpService::sendtoall,client,&UserClient::writedata);
    client->start();
    locker.unlock();
}
//delete a user client
void TcpService::deleteclient(qintptr socketDes)
{
    locker.lock();
    if(this->listclient->contains(socketDes))
    {
        UserClient*client=this->listclient->value(socketDes);
        delete client;
        client=nullptr;
        this->listclient->remove(socketDes);
    }
    locker.unlock();
}

void TcpService::sendtoclient(qintptr des, QByteArray arr)
{
    if(!this->listclient->contains(des))
    {
        return ;
    }
    this->listclient->value(des)->writedata(arr);
}
void TcpService::closeall()
{
    if(this->isListening())
    {
        this->close();
        qDeleteAll(this->listclient->begin(),this->listclient->end());
        this->listclient->clear();
    }
}
